package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.utils.ConnecctionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;
    private ConnecctionUtils connecctionUtils;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }
    public void setConnecctionUtils(ConnecctionUtils connecctionUtils) {
        this.connecctionUtils = connecctionUtils;
    }
    public List<Account> findAllAccount() {
        try{
            return runner.query(connecctionUtils.getConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer accountId) {
        try{
            return runner.query(connecctionUtils.getConnection(),"select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try{
            runner.update(connecctionUtils.getConnection(),"insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try{
            runner.update(connecctionUtils.getConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer accountId) {
        try{
            runner.update(connecctionUtils.getConnection(),"delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountByName(String name) {
        try{
            List<Account> accounts= runner.query(connecctionUtils.getConnection(),"select * from account where name = ? ",new BeanListHandler<Account>(Account.class),name);
            if(accounts==null || accounts.size()==0){return null;}
            //accounts.size是判断accounts数组的数值大小
            if (accounts.size()>1){
                throw  new RuntimeException("结果集不唯一");
            }
            //如果以上的都没有问题，则返回数组中的第一个值
            return accounts.get(0);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
